<template>
  <div class="account box">
    <div class="header-top">
      <div @click="leftBtn" class="arrow-left">
          <img src="../../images/left.png" alt="">
      </div>
    </div>
    <div class="bd-content">
      <div class="bd-address">
        <div
          v-if="!defaultAdress"
          class="address-none"
        >
          <span style="color:#666666">您还没有收货地址，</span>
          <span
            @click="linkTo('/myAddr')"
            class="span-add-adress"
          >去添加</span>
        </div>
        <div
          v-else
          @click="linkTo('/myAddr')"
          class="address-item"
        >
          <div class="name"><span style="margin-right:.25rem">{{defaultAdress.contactName}}</span>{{defaultAdress.telNumber}}</div>
          <div class="desc">{{defaultAdress.completeAddress}}</div>
          <div class="arrow"></div>
        </div>
      </div>
      <div v-if="type !='carts'">
        <Card
          :imgSrc="modeObj.modelImageUrl"
          :name="info.title"
        >
          <div class="good-desc">
            <span class="good-desc-info">{{modeObj.modelSize}}</span>
            <span class="good-desc-info">{{modeObj.modelName}}</span>
          </div>
          <div class="good-price">
            <span class="price-icon">积分：</span>
            <span class="good-price-num">{{modeObj.modelSalePrice}}</span>
          </div>
          <div class="good-count">
            <div
              @click="cutNum"
              class="count-change"
            >-</div>
            <div class="count-num">{{cartNum}}</div>
            <div
              @click="addNum"
              class="count-change"
            >+</div>
          </div>
        </Card>
      </div>
      <div v-else>
        <Card
          v-for="(item,index) in orderItems"
          :key="index"
          :imgSrc="item.imageUrl"
          :name="item.productName"
        >
          <div class="good-desc">
            <span class="good-desc-info">{{item.modelSize}}</span>
            <span class="good-desc-info">{{item.modelName}}</span>
          </div>
          <div class="good-price">
            <span class="price-icon">积分：</span>
            <span class="good-price-num">{{item.salePrice}}</span>
          </div>
          <div class="good-count">
            <div
              @click="cutNums(index,item.count)"
              class="count-change"
            >-</div>
            <div class="count-num">{{item.count}}</div>
            <div
              @click="addNums(index,item.count)"
              class="count-change"
            >+</div>
          </div>
        </Card>
      </div>
      <div class="bd-msg">
        <span class="msg-title">给商家留言:</span>
        <input
          class="msg-input"
          v-model="orderObj.memo"
          type="text"
          placeholder="不超过140字"
        >
      </div>
      <div class="bd-costs">
        <div class="cell">
          <span class="costs-name">商品积分</span>
          <span
            class="costs-num"
          >{{priceInfo.totalPrice}}</span>
        </div>
        <!-- <div class="cell">
          <span class="costs-name">优惠券</span>
          <div class="costs-tic">
            <div class="tic-num-tag">3张可用</div>
            <span class="costs-num tic">未使用</span>
            <div class="cell-right-arrow"></div>
          </div>
        </div>-->
        <!-- <div v-if="priceInfo&&priceInfo.discountPrice" class="cell">
          <span class="costs-name">会员折扣</span>
          <span class="costs-num">-￥{{priceInfo.discountPrice}}</span>
        </div>  -->
        <div class="cell">
          <span class="costs-name">运费</span>
          <span class="costs-num">{{priceInfo.fright?'积分：'+priceInfo.fright:'包邮'}}</span>
        </div>
      </div>
    </div>
    <div class="ft-totalInfo">
      <div class="totalInfo-cost">
        <span class="totalInfo-cost-title">实付积分:</span>
        <span class="totalInfo-cost-num">{{priceInfo.totalPrice}}</span>
      </div>
      <div
        @click="payBtn"
        :class="['totalInfo-pay-btn',{'cancel':!defaultAdress}]"
      >
        立即兑换
      </div>
    </div>
    <div v-transfer-dom>
      <confirm
        v-model="showBackDialog"
        confirm-text="确认"
        cancel-text="取消"
        @on-cancel="onCancel"
        @on-confirm="onConfirm"
      >
        <p class='dialog-content'>确认退出支付?</p>
      </confirm>
    </div>
    <div v-transfer-dom>
      <x-dialog v-model="showToast" class="dialog-demo">
         <x-input :max="6" label-width="1rem" title='密码' v-model="password" placeholder="请输入密码"></x-input>
        <div style="padding:15px;">
          <x-button @click.native="PayConfrim" type="primary" medium>确认兑换</x-button>
        </div>
      </x-dialog>
    </div>
  </div>
</template>

<script>
import { Confirm,XInput,XDialog, TransferDomDirective as TransferDom } from "vux";
import Card from "@/components/common/Goods-card.vue";
const testimg1 = require("../../images/test.png");
const addrBgImg = require("../../images/adres_icon@2x.png");
const balance = require("../../images/icon-balance.png");
const alipay = require("../../images/icon-alipay.png");
const wepay = require("../../images/icon-wepay.png");
import CONSTANT from "../../../wechat/static/constant/urlconstant";
import common from "../../../wechat/static/common/common";
import { types } from "util";
export default {
  directives: {
    TransferDom
  },
  data() {
    return {
      showToast:false,
      id: "",
      modeIndex: "",
      info: "",
      cartNum: "",
      modeObj: "",
      defaultAdress: "",
      fregit: "",
      fregitObj: {},
      orderObj: {
        addressId: "",
        memo: "",
        productList: [
          {
            count: 0,
            productCode: 0,
            modelCode: ""
          }
        ]
      },
      orderItems: [],
      type: "",
      payPrice: 0,
      index:'',
      cartNum:'',
      payType:'1',
      ids:'',
      priceInfo:'',

      balance,
      alipay,
      wepay,
      showBackDialog: false,
      password:''
    };
  },
  mounted() {
    let { id, index, cartNum, ids, type } = this.$router.currentRoute.query;
    this.type = type;
    this.id = id;
    this.cartNum = cartNum
    this.index = index;
    this.ids = ids
    if (type == "carts") {
      this.getInfos(ids);
    } else {
      this.modeIndex = index;
      this.cartNum = Number(cartNum);
      this.getInfo();
    }
    let addressObj =  common.getCookie('addressObj')
    if(addressObj){
      let address = JSON.parse(addressObj)
      address.districtName = address.districtName||''
      address.completeAddress = address.provinceName+address.cityName+address.districtName+address.detailedAddress
      console.log(this.defaultAdress,'this.defaultAdressthis.defaultAdress')
      this.orderObj.addressId = address.id
      this.defaultAdress = address
    }else{
      this.getDefaultAdress();
    }
  },

  watch: {
  },
  computed: {
  },
  beforeRouteLeave(to,from, next) {
    if (from.name == 'account' && to.name == 'goods-container') {
      this.$vux.confirm.show({
        title: '',
        content: '确认退出兑换?',
        confirmText: "取消",
        cancelText: "确定",
        onHide() {},
        onCancel() {
          next()
        },
        onConfirm() {
          next(false)
        },
      })
    } else {
      next()
    }
  },
  methods: {
    leftBtn(){
      this.$router.back(-1)
    },
    getInfos(ids) {
      let idsArr = ids.split(","),
        param = {
          pageIndex: 1,
          pageSize: 1000
        },
        url = CONSTANT.LIST.cartPage;
      common.post(url, param, res => {
        this.$vux.loading.hide();
        if (res.code == 200) {
          let arr = res.data.bussData;
          arr.forEach(item => {
            idsArr.map(list => {
              if (list == item.id) {
                this.orderItems.push(item);
              }
            });
          });
          console.log(this.orderItems,'orderItemsorderItemsorderItems')
          this.getPrice()
        }
      });
    },
    getPrice(){
      let productList = []
      if(this.type == 'carts'){
        this.orderItems.map(item => {
          productList.push({
            count: item.count,
            productId: item.productId,
            modelCode: item.modelCode
          });
        });
      }else{
        productList.push({
          count: this.cartNum,
          productId: this.info.id,
          modelCode: this.modeObj.modelCode
        });
      }

       let url = CONSTANT.LIST.previewOrder;
      common.post(url, {productList:productList}, res => {
        if (res.code == 200) {
          let data = res.data.bussData;
          this.priceInfo = data
        }
      });
      
    },
    getInfo() {
      let url = CONSTANT.LIST.PRDOUCTBYID;
      common.get(url, this.id, res => {
        if (res.code == 200) {
          this.info = res.data.bussData;
          this.modeObj = this.info.modelList[this.modeIndex];
          this.getPrice()
        }
      });
    },
    addNums(index, count) {
      let arr = this.orderItems;
      arr[index].count++;
      this.getPrice()
    },
    cutNums(index, count) {
      let arr = this.orderItems;
      if (count <= 1&&this.orderItems.length<2) return;
      arr[index].count--;
      this.getPrice()
      if(arr[index].count <1){
        this.orderItems.splice(index,1);
      }
    },
    addNum() {
      let { firstItem, secondary } = this.fregitObj;
      this.cartNum += 1;
      this.getPrice()
    },
    cutNum() {
      let { firstItem, secondary } = this.fregitObj;
      if (this.cartNum <= 1) return;
      this.cartNum -= 1;
      this.getPrice()
    },
    getDefaultAdress() {
      let url = CONSTANT.LIST.ADDRESSFAULT;
      common.get(url, "", res => {
        if (res.code == 200) {
          this.defaultAdress = res.data.bussData || null;
          if(!this.defaultAdress) return
          this.orderObj.addressId = res.data.bussData.id;
        }
      });
    },
    payBtn(){
      this.password = ''
      this.showToast = true
    },
    PayConfrim() {
      let params = {
          addressId: "",
          memo: "",
          productList: [
            {
              count: 0,
              id: 0,
              modelCode: ""
            }
          ]
        },
        obj = this.orderObj;
      if (this.type == "carts") {
        params.addressId = obj.addressId;
        params.memo = obj.memo;
        params.productList = [];
        params.shoppingCatIds =  this.ids.split(",")
        this.orderItems.map(item => {
          params.productList.push({
            count: item.count,
            productId: item.productId,
            modelCode: item.modelCode
          });
        });
      } else {
        obj.productList[0].count = this.cartNum;
        obj.productList[0].productId = this.info.id;
        obj.productList[0].modelCode = this.modeObj.modelCode;
        params = obj;
      }
      this.$vux.loading.show({
        text: "提交中"
      });
      let url = CONSTANT.LIST.createOrderCode;
      common.post(url, params, res => {
        this.$vux.loading.hide();
        
        if (res.code == 200) {
          this.wxPay(res.data.bussData.orderCode);
        } else {
          this.showToast = false
          this.$vux.toast.show({
            type: "cancel",
            text: res.data.errMsg
          });
        }
      });
    },
    wxPay(order) {
      let url = `${CONSTANT.LIST.payOrder}`;
      common.post(url, {
        orderCode:order,
        pwd:this.password
      }, res => {
        this.$vux.loading.hide();
        this.showToast = false
        if (res.code == 200) {
         this.$vux.toast.show({
            type: "success",
            text: '兑换成功'
          });
          this.$router.replace({
            path:'detailComplete',
            query:{
              code:order
            }
          })
        } else {
          this.$vux.toast.show({
            type: "cancel",
            text: res.data.errMsg
          });
        }
      });
    },
    //调起微信支付
    wechatPay(param,order) {
      let that = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: param.appId, //公众号名称，由商户传入
          timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: param.nonceStr, //随机串
          package:param.packageValue,
          signType:param.signType, //微信签名方式：
          paySign: param.paySign //微信签名
        },
        function(res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            that.checkPay(order)
          }
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        }
      );
    },
    checkPay(order){
      let url = CONSTANT.LIST.payCheck;
      common.get(url, `/${order}`, res => {
        if (res.code == 200) {
          let data = res.data.bussData.returnCode
          if(data == 'SUCCESS'){
            this.$router.replace('/finalPay?id='+order)
          }
        }
      });
    },
    linkTo(link) {
      this.$router.push(`${link}?id=${this.id}&index=${this.index}&cartNum=${this.cartNum}`);
    },
    pushHistory() {
      let state = {
        title: "title",
        url: `#account?id=${this.id}&index=${this.index}&cartNum=${this.cartNum}&ids=${this.ids}&type=${this.type}`
      };
      window.history.pushState(state, "title", `#account?id=${this.id}&index=${this.index}&cartNum=${this.cartNum}&ids=${this.ids}&type=${this.type}`);
    },
    onConfirm() {
      this.showBackDialog = false;
//      window.history.back();
    },
    onCancel() {
      return;
//      this.pushHistory();
    }
  },
  destroyed(){
    common.setCookie('addressObj','')
  },
  components: {
    Card,
    Confirm,
    XDialog,
    XInput
  }
};
</script>


<style lang="less">
body,
html {
  background: #f7f7f7;
}
.account {
  font-family: PingFang-SC-Light;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .header-top{
    height: .8rem;
    line-height: .8rem;
    background-color: #fff;
    .arrow-left{
      position: absolute;
      left: .1rem;
      top: .1rem;
      height: .9rem;
      width: 1rem;
      z-index: 99;
      img{
        height: .5rem;
        width: .5rem;
      }
    }
  }
  .weui-dialog{
    font-size: .32rem;
  }
  .weui-label, .weui-input{
    font-size: .32rem;
  }
  .bd-content {
    width: 100%;
    margin-bottom: 0.98rem;
    .card {
      padding-left: 0.23rem;
      padding-top: 0.29rem;
      height: inherit;
      align-items: inherit;
      img {
        width: 2rem;
        height: 2rem;
      }
      .goods-item-content {
        height: auto;
        padding-top: 0;
        .item-name {
          // padding-top: .1rem;
        }
      }
    }
    .good-desc {
      .good-desc-info {
        font-size: 0.26rem;
        font-family: PingFang-SC-Light;
        color: rgba(158, 158, 158, 1);
        line-height: 0.5rem;
        margin-right: 0.2rem;
      }
    }
    .good-price {
      position: absolute;
      bottom: 0rem;
      color: rgba(126, 86, 198, 1);
      .good-price-num {
        font-size: 0.31rem;
        font-family: PingFang-SC-Light;
        line-height: 0.52rem;
      }
    }
    .good-price-del {
      font-size: 0.23rem;
      font-family: PingFang-SC-Light;
      text-decoration: line-through;
      color: rgba(153, 153, 153, 1);
      line-height: 0.4rem;
    }
    .good-count {
      position: absolute;
      bottom: 0rem;
      right: 0.6rem;
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      text-align: center;
      height: 0.47rem;
      line-height: 0.47rem;

      .count-change {
        color: rgba(175, 175, 175, 1);
        width: 0.54rem;
        border: 0.02rem solid rgba(175, 175, 175, 1);
        font-size: 0.3rem;
      }
      .count-num {
        width: 1.1rem;
        border-top: 0.02rem solid rgba(175, 175, 175, 1);
        border-bottom: 0.02rem solid rgba(175, 175, 175, 1);
        font-size: 0.28rem;
      }
    }
    .bd-msg {
      background: white;
      padding-right: 0.25rem;
      padding-left: 0.25rem;
      height: 0.8rem;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      .msg-title {
        font-size: 0.25rem;
        color: rgba(102, 102, 102, 1);
      }
      .msg-input {
        flex: 1;
        padding-left: 0.3rem;
        font-size: 0.26rem;
      }
      .msg-input::-webkit-input-placeholder {
        text-align: right;
        font-family: PingFang-SC-Medium;
        font-size: 0.24rem;
        color: #999999;
      }
    }
    .bd-pay {
      padding-left: 0.28rem;
      box-sizing: border-box;
      .pay-title {
        height: 0.77rem;
        color: rgba(154, 154, 154, 1);
        font-size: 0.26rem;
        line-height: 0.77rem;
        border-bottom: 0.01rem solid rgba(245, 245, 245, 1);
      }
      .pay-type {
        height: 0.9rem;
        display: flex;
        flex-direction: row;
        align-items: center;

        .pay-type-icon {
          width: 0.45rem;
          height: 0.45rem;
        }
        .pay-type-content {
          flex: 1;
          margin-left: 0.28rem;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          border-bottom: 0.01rem solid rgba(245, 245, 245, 1);
          height: 100%;
          .pay-type-name {
            font-size: 0.3rem;
          }
          .pay-type-num {
            font-size: 0.25rem;
          }
          .type-radio {
            width: 0.4rem;
            height: 0.4rem;
            margin-right: 0.29rem;
            input {
              -webkit-appearance: radio;
              position: relative;
              opacity: 0;
              width: 0.4rem;
              height: 0.4rem;
              z-index: 2;
            }
            .radio-css {
              bottom: 0.52rem;
              position: relative;
            }
            .radio-css::before {
              display: inline-block;
              content: "";
              background: white;
              border-radius: 50%;
              width: 0.39rem;
              height: 0.39rem;
              border: 0.01rem solid #aeaeae;
              vertical-align: bottom;
            }
            input:checked + .radio-css::after {
              display: inline-block;
              content: "";
              width: 0.17rem;
              height: 0.17rem;
              border-radius: 50%;
              position: absolute;
              left: 0.12rem;
              bottom: 0.08rem;
              background-color: rgba(126, 86, 198, 1);
            }
          }
        }
      }
    }
    .bd-address {
      width: 100%;
      height: 1.98rem;
      background: rgba(246, 246, 246, 1);
      display: flex;
      justify-content: center;
      align-items: center;
      .address-none {
        background-image: url("../../images/adres_icon@2x.png");
        display: flex;
        justify-content: center;
        align-items: center;
        background-size: 100% 100%;
        height: 1.6rem;
        width: 94%;
        font-size: 0.27rem;
        color: #545353;
        border-radius: 0.1rem;
        .span-add-adress {
          color: #7e56c6;
        }
      }
      .address-item {
        position: relative;
        background-image: url("../../images/adres.png");
        background-size: 100%;
        width: 7.02rem;
        height: 1.6rem;
        .name {
          padding-left: 0.25rem;
          padding-top: 0.4rem;
          font-size: 0.28rem;
          font-family: PingFang-SC-Medium;
          font-weight: 500;
          color: rgba(34, 34, 34, 1);
        }
        .desc {
          font-size: 0.26rem;
          font-family: PingFang-SC-Medium;
          font-weight: 500;
          color: rgba(102, 102, 102, 1);
          margin-top: 0.1rem;
          padding-left: 0.25rem;
        }
        .arrow {
          position: absolute;
          right: 0.2rem;
          top: 0.8rem;
          background-image: url("../../images/fanhui@2x.png");
          background-size: 100%;
          width: 0.12rem;
          height: 0.22rem;
        }
      }
    }
    .bd-costs {
      margin-top: 0.15rem;
      width: 100%;
      background: white;
      .cell {
        height: 0.8rem;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        padding-left: 0.23rem;
        padding-right: 0.23rem;
        .costs-name {
          color: rgba(102, 102, 102, 1);
          font-size: 0.25rem;
        }
        .costs-num {
          color: black;
          font-size: 0.28rem;
        }
        .tic {
          margin-right: 0.18rem;
        }
        .costs-tic {
          display: flex;
          flex-direction: row;
          align-items: center;
          .tic-num-tag {
            font-size: 0.22rem;
            color: white;
            background-color: #ffc62e;
            width: 1.02rem;
            height: 0.4rem;
            line-height: 0.4rem;
            text-align: center;
            margin-right: 0.25rem;
          }
          .cell-right-arrow {
            width: 7px;
            height: 7px;
            border-top: 0.01rem solid #aaa;
            border-right: 0.01rem solid #aaa;
            transform: rotate(45deg);
          }
        }
      }
    }
  }
  .ft-totalInfo {
    border-top: 0.01rem solid rgba(0, 0, 0, 0.08);
    border-bottom: 0.01rem solid rgba(0, 0, 0, 0.08);
    display: flex;
    left: 0;
    right: 0;
    position: fixed;
    z-index: 995;
    bottom: 0;
    flex-direction: row;
    align-items: center;
    padding-left: 0.25rem;
    justify-content: space-between;
    background: white;
    height: 0.97rem;
    .totalInfo-cost {
      .totalInfo-cost-title {
        font-size: 0.25rem;
        color: #333333;
      }
      .totalInfo-cost-num {
        font-size: 0.35rem;
        font-weight: bold;
        color: rgba(126, 86, 198, 1);
      }
    }
    .totalInfo-pay-btn {
      display: flex;
      width: 2rem;
      height: 100%;
      color: white;
      font-size: 0.25rem;
      background: #7e56c6;
      justify-content: center;
      align-items: center;
      &.cancel{
        background: #CBBBE8;
      }
    }
  }
}
.disable {
  opacity: 0.3;
}
</style>
